package com.example.pdfprocessor.controller;

import com.example.pdfprocessor.service.WordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping("/word")
@RequiredArgsConstructor
@Slf4j
public class WordController {

    private final WordService wordService;

    @GetMapping
    public String index() {
        return "word";
    }

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
                                  RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择文件上传");
            return "redirect:/word";
        }

        try {
            // 检查文件是否为Word文档 (.doc或.docx)
            String originalFilename = file.getOriginalFilename();
            String contentType = file.getContentType();
            log.info("上传文件类型: {}, 文件名: {}, 大小: {}", contentType, originalFilename, file.getSize());
            
            if (originalFilename == null || 
                !(originalFilename.endsWith(".docx") || originalFilename.endsWith(".doc"))) {
                redirectAttributes.addFlashAttribute("message", "只支持Word文档格式 (.doc或.docx)");
                return "redirect:/word";
            }

            String filename = wordService.processWordDocument(file);
            log.info("文件处理成功，生成的文件名: {}", filename);
            
            // 将文件名添加到重定向属性中
            redirectAttributes.addFlashAttribute("filename", filename);
            redirectAttributes.addFlashAttribute("message", "文件处理成功");
            
            // URL编码文件名以避免特殊字符问题
            String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            log.info("重定向到预览页面，URL编码后的文件名: {}", encodedFilename);
            
            return "redirect:/word/preview?filename=" + encodedFilename;
        } catch (IOException e) {
            log.error("文件处理失败", e);
            // 生成用户友好的错误消息
            String errorMsg = "文件处理失败";
            if (e instanceof FileNotFoundException || e.getMessage().contains("系统找不到指定的路径")) {
                errorMsg = "文件存储路径错误，请联系管理员检查系统配置";
            } else {
                errorMsg = "文件处理失败: " + e.getMessage();
            }
            redirectAttributes.addFlashAttribute("message", errorMsg);
            return "redirect:/word";
        } catch (Exception e) {
            log.error("发生未知错误", e);
            redirectAttributes.addFlashAttribute("message", "处理过程中发生错误: " + e.getMessage());
            return "redirect:/word";
        }
    }

    @GetMapping("/preview")
    public String previewPage(@RequestParam("filename") String filename, Model model) {
        log.info("进入预览页面，接收到的文件名参数: {}", filename);
        
        File file = wordService.getWordFile(filename);
        log.info("查找文件: {}, 文件是否存在: {}", file.getAbsolutePath(), file.exists());
        
        if (!file.exists()) {
            log.error("找不到文件: {}", file.getAbsolutePath());
            model.addAttribute("errorMessage", "找不到文件，可能已被删除");
            return "error";
        }
        
        // 设置模型属性
        model.addAttribute("filename", filename);
        model.addAttribute("downloadUrl", "/word/download/" + filename);
        
        // 记录日志，帮助调试
        log.info("准备预览Word文件：{}, 文件存在，渲染word-preview模板", file.getAbsolutePath());
        
        // 返回预览页面视图名称
        return "word-preview";
    }

    @GetMapping("/download/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        log.info("下载文件请求: {}", filename);
        File file = wordService.getWordFile(filename);
        
        if (!file.exists()) {
            log.error("文件不存在: {}", file.getAbsolutePath());
            return ResponseEntity.notFound().build();
        }
        
        Resource resource = new FileSystemResource(file);
        log.info("文件存在，准备下载: {}", file.getAbsolutePath());
        
        // 设置正确的Content-Type
        MediaType mediaType;
        if (filename.endsWith(".docx")) {
            mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        } else {
            mediaType = MediaType.parseMediaType("application/msword");
        }

        return ResponseEntity.ok()
                .contentType(mediaType)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .body(resource);
    }
} 